/**
 * getASRStat 云函数
 * 用于获取语音识别任务的状态
 */

// 导入所需的模块
const fs = require('fs');
const path = require('path');
const tencentcloud = require('tencentcloud-sdk-nodejs');
const CloudBase = require('@cloudbase/node-sdk');

// 初始化云开发SDK
const cloud = CloudBase.init({
  env: CloudBase.SYMBOL_CURRENT_ENV
});

// 初始化腾讯云ASR客户端
const AsrClient = tencentcloud.asr.v20190614.Client;
const models = tencentcloud.asr.v20190614.Models;


const clientConfig = {
  credential: {
    secretId: process.env.TENCENT_SECRET_ID,
    secretKey: process.env.TENCENT_SECRET_KEY,
  },
  region: process.env.TENCENT_REGION || 'ap-guangzhou', // 默认使用广州区域，可以根据需要修改
  profile: {
    httpProfile: {
      endpoint: 'asr.tencentcloudapi.com',
    },
  },
};


// 云函数入口函数
exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { taskId } = event;
    
    // TODO: 实现获取ASR任务状态的逻辑
    
    asrResult = "";

    // 调用腾讯云ASR服务
    const client = new AsrClient(clientConfig);

    paramsStat = {
      TaskId: taskId, // 替换为你的任务 ID
    };

    //params.TaskId = taskId;
    const descData = await client.DescribeTaskStatus(paramsStat);

    console.log('查询结果:', descData);

    // 检查任务状态
    switch (descData.Data.Status) {
      case 0: // 排队中
        return {
          code: 0,
          ASRStatus: 0,
          message: '任务排队中',
          data: {
            taskId,
          },
        };
      case 1: // 进行中
        return {
          code: 0,
          ASRStatus: 1,
          message: '任务进行中',
          data: {
            taskId,
          },
        };
      case 2: // 任务完成
        asrResult = descData.Data.Result;
        return {
          code: 0,
          ASRStatus: 2,
          message: 'success',
          data: {
            asrResult,
          },
        };
      case 3: // 任务失败
        return {
          code: 500,
          ASRStatus: 3,
          message: '语音识别失败',
          error: descData.Data.ErrorMsg,
        };
      default:
        return {
          code: 500,
          ASRStatus: -1,
          message: '未知的任务状态',
          data: {
            status: descData.Data.Status,
          },
        };
    }

  }
  catch (error) {
    console.error('语音识别过程中发生错误:', error);
    return {
      code: 500,
      message: '语音识别过程中发生错误',
      error: error.message || error,
    };
  }
};